package cn.zhentao.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis Plus 配置类
 * 
 * @author zhentao
 * @since 2024-07-28
 */
@Configuration
public class MybatisPlusConfig {

    // MyBatis Plus 拦截器配置已移至具体的服务模块中
    // 避免Bean定义冲突

    /**
     * 自动填充处理器
     * 自动填充创建时间、更新时间等字段
     */
    @Component
    public static class MyMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            // 创建时间
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
            
            // 更新时间
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now());
            
            // 创建者
            this.strictInsertFill(metaObject, "createBy", String.class, "system");
            this.strictInsertFill(metaObject, "createdBy", String.class, "system");
            
            // 更新者
            this.strictInsertFill(metaObject, "updateBy", String.class, "system");
            this.strictInsertFill(metaObject, "updatedBy", String.class, "system");
            
            // 逻辑删除标志
            this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
            this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0);
            
            // 版本号（乐观锁）
            this.strictInsertFill(metaObject, "version", Integer.class, 1);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            // 更新时间
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now());
            
            // 更新者
            this.strictUpdateFill(metaObject, "updateBy", String.class, "system");
            this.strictUpdateFill(metaObject, "updatedBy", String.class, "system");
        }
    }
}
